package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.model.entity.SysAuditColumn;
import com.settlement.system.mapper.SysAuditColumnMapper;
import com.settlement.system.model.query.AuditColumnPageQuery;
import com.settlement.system.model.vo.AuditConfigImportVO;
import com.settlement.system.model.vo.BillConfigImportVO;
import com.settlement.system.service.SysAuditColumnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 标准核销表字段对应关系 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-07
 */
@Service
public class SysAuditColumnServiceImpl extends ServiceImpl<SysAuditColumnMapper, SysAuditColumn> implements SysAuditColumnService {

    @Override
    public Page<SysAuditColumn> getAuditColumnPage(AuditColumnPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String platform = queryParams.getPlatform();
        // 查询数据
        Page<SysAuditColumn> auditColumnPage = this.page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<SysAuditColumn>().like(StrUtil.isNotBlank(platform), SysAuditColumn::getPlatform, platform));

        return auditColumnPage;
    }

    @Override
    public void importConfig(List<AuditConfigImportVO> rows, String platform) {
        List<SysAuditColumn> sysAuditColumns = new ArrayList<>();
        // 查出所有配置到的历史记录
        List<SysAuditColumn> list = this.list(new LambdaQueryWrapper<SysAuditColumn>().eq(SysAuditColumn::getPlatform, platform));
        for (AuditConfigImportVO row : rows) {
            SysAuditColumn auditColumn = list.stream().filter(sysAuditColumn -> sysAuditColumn.getSourceTable().equals(row.getSourceTable())).findFirst().orElse(null);
            if (auditColumn != null) {
                BeanUtil.copyProperties(row, auditColumn, "id");
                sysAuditColumns.add(auditColumn);
            } else {
                SysAuditColumn sysAuditColumn = new SysAuditColumn();
                BeanUtil.copyProperties(row, sysAuditColumn);
                sysAuditColumn.setPlatform(platform);
                sysAuditColumns.add(sysAuditColumn);
            }
        }
        this.saveOrUpdateBatch(sysAuditColumns);
    }

    @Override
    public List<SysAuditColumn> getAll() {
        return this.list();
    }

    @Override
    public List<SysAuditColumn> getAllByPlatform(String platform) {
        return this.list(new LambdaQueryWrapper<SysAuditColumn>().eq(SysAuditColumn::getPlatform, platform));
    }


}
